import { Form, Input, Divider, Card, Col, Row, message } from 'antd';
import React, { useState, useEffect } from 'react';
import { HTTP_STATUS } from "@/generic/ConfigParams";

const FormItem = Form.Item;

const requestDecorator = async (requestFunc, msgTip = '', modalAction) => {
    const hide = message.loading(`正在${msgTip}`);
    const response = await requestFunc;
    hide();
    console.log('==>> requestDecorator', response)
    if (response && response.ok) {
        message.success(`${msgTip}成功`);
        modalAction;  // 使用了Modal时，此处操作 modalVisible
    }
    else {
        const error_msg = response.status ? HTTP_STATUS[response.status] : "";
        message.error(`${msgTip}失败！${error_msg}`);
    }
}

const UpdateForm = props => {

    const { dispatch, currentPage, objInfo, form, detailArgs } = props;
    const { updateTitle, leave, content: contentItems, footer: footerArr, } = detailArgs;
    const [footer, setFooter] = useState('');
    const MARK = 'update';

    const renderContent = () => {

        const formItems = [];

        if (contentItems && currentPage) {
            for (const key in contentItems) {

                contentItems[key].length > 0
                && contentItems[key].forEach((item, i) => {
                    
                    if (item.canUpdate) {
                        const { elem, isRow, isMine, index, labelCol, wrapperCol, handle } = item;
                        const Elem = elem || <Input />;
                        const colSpan = isRow || detailArgs.defaultColSpan;
                        const text = handle ? handle(objInfo[index]) : objInfo[index];
                        const initValue = isMine ? objInfo[isMine.defaultIndex] : text;
                        formItems.push(
                            <Col key={`${key}_${i}`} {...colSpan}>
                                <FormItem
                                    labelCol={labelCol || detailArgs.defaultLabelCol}
                                    wrapperCol={wrapperCol || detailArgs.defaultWrapperCol}
                                    label={item.label}
                                >
                                    {form.getFieldDecorator(index, {
                                        ...item.options,
                                        initialValue: initValue
                                    })(Elem)}
                                </FormItem>
                            </Col>
                        )
                    } 
                })
                // formItems.push(<Divider key={formItems.length} />)
            }
        }

        return <Row gutter={[16, 16]}>{formItems}</Row>;
    }

    const onClick = (item) => {
        if (item.isValidate) {
            form.validateFields((err, fieldsValue) => {
                if (err) return;
                console.log("==>>validateFields", fieldsValue)
                const updateFields = {};
                for (const key in fieldsValue) {
                    
                    if (form.isFieldTouched(key)) {  // 判断哪些值更改了
                        updateFields[key] = fieldsValue[key];
                    }
                }
                if (!Object.keys(updateFields).length > 1) return;
                // console.log('===>> updateFields:', updateFields)
                requestDecorator(item.onClick(dispatch, objInfo, updateFields), item.text);
            });
        }
        else {
            item.onClick(dispatch);
        }

        form.resetFields();
    }

    const renderFooter = () => {
        const footerOpts = [];

        if (footerArr) {
            footerArr.forEach((item, i) => {
                (!item.mark || item.mark == MARK)
                && footerOpts.push(
                    <div key={i} style={{ ...item.style }}>
                        <item.elem {...item.args}
                            onClick={() => onClick(item)}
                        >{item.text}</item.elem>
                    </div>
                )
            })
        }
        return <>{footerOpts}</>;
    }

    useEffect(() => {
        // console.log("==>> contentItems!", contentItems)
        setFooter(renderFooter());
    }, [contentItems])

    useEffect(() => {
        console.log('===>> currentPage', currentPage)
    }, [currentPage])

    return (
        <div style={{ backgroundColor: "#fff" }}>
            <Card
                title={updateTitle}
            // extra={extraRender()}
            >
                {renderContent()}
                <Divider />
                {footer}
            </Card>
        </div>
    );
}

export default Form.create()(UpdateForm);